'use server'

import { prisma } from '@/lib/prisma'
import { revalidatePath } from 'next/cache'
import { Decimal } from '@prisma/client/runtime/library'

interface CreateInboundData {
  supplierId: string
  items: {
    productId: string
    quantity: string
    price: string
  }[]
}

export async function createInbound(data: CreateInboundData) {
  try {
    // 生成入库单号
    const code = `RK${Date.now()}`
    
    // 计算总金额
    const totalAmount = data.items.reduce((sum, item) => {
      const itemAmount = new Decimal(item.price).mul(new Decimal(item.quantity))
      return sum.add(itemAmount)
    }, new Decimal(0))

    const now = new Date() // 创建当前时间戳

    const purchase = await prisma.purchase.create({
      data: {
        code,
        supplierId: parseInt(data.supplierId),
        totalAmount,
        status: 'PENDING',
        createdAt: now,
        updatedAt: now,
        items: {
          create: data.items.map(item => ({
            productId: parseInt(item.productId),
            quantity: parseInt(item.quantity),
            price: new Decimal(item.price),
            amount: new Decimal(item.price).mul(new Decimal(item.quantity)),
            createdAt: now,
            updatedAt: now
          }))
        }
      },
      include: {
        supplier: true,
        items: {
          include: {
            product: true
          }
        }
      }
    })

    // 序列化返回数据
    const serializedPurchase = {
      ...purchase,
      totalAmount: purchase.totalAmount.toString(),
      items: purchase.items.map(item => ({
        ...item,
        price: item.price.toString(),
        amount: item.amount.toString(),
        product: {
          ...item.product,
          price: item.product.price.toString()
        }
      }))
    }

    revalidatePath('/dashboard/inventory/inbound')
    return { success: true, data: serializedPurchase }
  } catch (error) {
    console.error('创建入库单失败:', error)
    return { 
      success: false, 
      error: error instanceof Error ? error.message : '创建入库单失败'
    }
  }
}

export async function completeInbound(id: number) {
  try {
    const purchase = await prisma.$transaction(async (tx) => {
      // 1. 获取入库单及其明细
      const purchase = await tx.purchase.findUniqueOrThrow({
        where: { id },
        include: {
          items: true
        }
      })

      if (purchase.status !== 'PENDING') {
        throw new Error('该入库单状态不正确')
      }

      // 2. 更新商品库存
      for (const item of purchase.items) {
        await tx.product.update({
          where: { id: item.productId },
          data: {
            stock: {
              increment: item.quantity
            }
          }
        })
      }

      // 3. 更新入库单状态
      return await tx.purchase.update({
        where: { id },
        data: {
          status: 'COMPLETED',
          updatedAt: new Date()
        },
        include: {
          supplier: true,
          items: {
            include: {
              product: true
            }
          }
        }
      })
    })

    // 序列化返回数据
    const serializedPurchase = {
      ...purchase,
      totalAmount: purchase.totalAmount.toString(),
      items: purchase.items.map(item => ({
        ...item,
        price: item.price.toString(),
        amount: item.amount.toString(),
        product: {
          ...item.product,
          price: item.product.price.toString()
        }
      }))
    }

    revalidatePath('/dashboard/inventory/inbound')
    return { success: true, data: serializedPurchase }
  } catch (error) {
    console.error('完成入库失败:', error)
    return { 
      success: false, 
      error: error instanceof Error ? error.message : '完成入库失败'
    }
  }
} 